<template>
  <div class="main">
    <div v-for="item in list" class="item" :key="item.username" @click="openChat(item)">
      <el-badge :value="item.count" class="item">
        <app-avatar :size="50" :src="item.avatarUrl"></app-avatar>
        <span>{{ item.nickName }}</span>
      </el-badge>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {getCustomerUnreadMap, handleOneMessage} from "@/api/customer";
import {ICustomerInfo, ICustomerUnRead} from "@/api/types/customer";
import {store} from "@/store";
import {ICustomer} from "@/types/store/customer";
import {IChatMessage} from "@/api/types/chat";

const list = ref<ICustomerUnRead[]>([])

onMounted(async () => {
  // 加载初始化数据
  list.value = await getCustomerUnreadMap() || []
})

// TODO 客服登录
const url = import.meta.env.VITE_API_BASEURL
let se: EventSource // 连接对象
watch(() => store.state.customer.user, (user) => {
  login(store.state.customer, user)
})
const login = (state: ICustomer, user: ICustomerInfo) => {
  if (se) {
    se.close()
  }
  // 连接sse
  se = new EventSource(`${url}/sseCustomerLogin/${user.openId}`)
  console.log(se)
  se.onmessage = (e) => {
    try {
      const data = JSON.parse(e.data) as IChatMessage
      if (!data) {
        return;
      }
      handleMessage(data)
    } catch (err) {
      console.log('客服消息处理失败！', err)
    }
  }
  se.onerror = (e) => {
    store.state.customer.loginId = 0
  }
}

// TODO 消息处理
const handleMessage = async (msg: IChatMessage) => {
  console.log(msg)
  if (msg.type! >= 10) {
    // 系统消息
    if (msg.type === 11) {
      // TODO 客戶通知已讀消息
      const item = store.state.customer.chatList.find((i) => {
        return i.id === msg.id
      })
      if (item) {
        item.status = 1
      }
    } else if (msg.type === 12) {
      // TODO 客戶通知進入了聊天窗口
      if (store.state.customer.activeUser?.username === msg.from) {
        store.state.customer.chatList.forEach((item) => {
          item.status = 1
        })
      }
    } else if (msg.type === 21) {
      // 1. 有客服打开页面/或者进行消息处理
      let index = list.value?.findIndex((i) => i.username === msg.from)
      if (index !== -1) {
        // 删除记录
        list.value?.splice(index!, 1)
      }
      // 2. 朋友列表如果存在聊天记录清 0
      if (store.state.customer.friendList) {
        index = store.state.customer.friendList?.findIndex((i) => i.username === msg.from)
        if (index !== -1) {
          // 更新记录
          store.state.customer.friendList![index!].count = 0
        }
      }
    } else if (msg.type === 31) { // 登录提醒
      store.state.customer.loginId = msg.id!  // 这是连接id
    }
  } else {
    // 客服消息
    if (msg.to === 'customer_system') {
      // TODO 用户主动发的客服消息
      if (store.state.customer.activeUser?.username === msg.from) {
        // 正在打开当前客服消息窗口
        store.state.customer.chatList.push(msg)
        store.state.customer.chatUpdateId++
        // 1.更新朋友列表
        let index = -1
        if (store.state.customer.friendList) {
          index = store.state.customer.friendList?.findIndex((i) => i.username === msg.from)
          if (index !== -1) {
            // 更新记录
            const obj = store.state.customer.friendList![index!]
            obj.message = msg.message!
            obj.type = msg.type!
            obj.createTime = msg.createTime!
          } else {
            // 不存在则插入
            store.state.customer.friendList?.push({
              avatarUrl: msg.avatar!,
              username: msg.from!,
              count: 0,
              nickName: msg.nickName!,
              type: msg.type!,
              createTime: msg.createTime!,
              message: msg.message!
            })
          }
        } else {
          // 不存在则设置
          store.state.customer.friendList = [{
            avatarUrl: msg.avatar!,
            username: msg.from!,
            count: 0,
            nickName: msg.nickName!,
            type: msg.type!,
            createTime: msg.createTime!,
            message: msg.message!
          }]
        }
        // 2.主动通知服务器消息已处理
        await handleOneMessage(msg.id!, msg.from!)

      } else {
        // TODO 新增处理判断
        if (msg.handle === 0) {
          // 1.更新待处理未读记录
          const user = list.value?.find((i) => i.username === msg.from)
          if (!user) {
            // 不存在则插入
            list.value?.push({
              avatarUrl: msg.avatar!,
              username: msg.from!,
              count: 1,
              nickName: msg.nickName!
            })
          } else {
            // 存在则累加
            user.count++
          }
        }
        // 2.更新朋友列表未读记录（如果列表存在的话）
        // 2. 朋友列表如果存在聊天记录清 0
        const index = store.state.customer.friendList?.findIndex((i) => i.username === msg.from)
        if (index !== -1) {
          // 更新记录
          const obj = store.state.customer.friendList![index!]
          if (msg.handle === 0) {
            obj.count++ // 不更新次数
          }
          obj.message = msg.message!
          obj.type = msg.type!
          obj.createTime = msg.createTime!
        }

      }
    } else {
      // TODO 客服人员发送的消息
      if (msg.to === store.state.customer.activeUser?.username) {
        // 当前聊天窗口是否打开
        store.state.customer.chatList.push(msg)
        store.state.customer.chatUpdateId++
      }
      // 判斷朋友列表是否存在記錄
      if (store.state.customer.friendList) {
        const item = store.state.customer.friendList.find((i) => {
          return i.username === msg.to
        })
        if (item) {
          item.message = msg.message!
          item.type = msg.type!
          item.createTime = msg.createTime!
        }
      }
      // TODO 消息是否本人发送-涉及调整朋友列表顺序
      if (msg.from === store.state.customer.user?.openId) {
        const index = store.state.customer.friendList?.findIndex((i) => {
          return i.username === msg.to
        })
        if (index === -1) {
          // 朋友列表不存在-插入前面
          store.state.customer.friendList!.unshift({
            avatarUrl: store.state.customer.activeUser?.avatarUrl!,
            username: store.state.customer.activeUser?.username!,
            count: 0,
            nickName: store.state.customer.activeUser?.nickName!,
            type: msg.type!,
            createTime: msg.createTime!,
            message: msg.message!
          }) // 插入前面
        } else if (index !== 0) {
          // 不是第一位则更新位置
          const _back = store.state.customer.friendList![index!]
          store.state.customer.friendList?.splice(index!, 1)
          store.state.customer.friendList!.unshift(_back) // 插入前面
        }
      }
    }
  }
}

// 更新消息记录
watch(list, () => {
  if (list.value) {
    store.state.customer.pendingMessage = list.value?.reduce((pre, cur) => {
      return pre + cur.count
    }, 0)!
    store.state.customer.pendingUser = list.value?.length!
  }
}, {
  deep: true
})

// 监听切换聊天客户动作
// watch(() => store.state.customer.activeUser!, async (user: IChatUser) => {
//   if (!user) {
//     return
//   }
//   // 1. 查询客户是待处理消息记录数
//   const count = await getCustomerUnreadCount(user.username, store.state.customer.user.openId!)
//   // 2. 查询聊天信息
//   store.state.customer.chatList = await queryMessageList({
//     username: user.username,
//     unread: count!
//   })
// })

// 打開窗口
const openChat = (item: ICustomerUnRead) => {
  store.commit('customer/setActiveUser', item)
}
</script>

<style lang="scss" scoped>
div.main {
  display: grid;
  grid-gap: 9px 9px;
  justify-content: center;
  grid-template-columns: repeat(auto-fill, minmax(65px, 1fr));
  width:98%;
  max-height: calc(100vh - 135px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 13px;
  padding-top: 5px;
}

div.item {
  width: 96%;
  height: 70px;
  margin: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  cursor: pointer;
  color: #4c4d4f;
  box-sizing: border-box;
  background: #e5e5e8;

  animation: blink;
  animation-duration: 0.7s;
  animation-iteration-count: infinite;
  border-radius: 5px;

  & > span {
    width: 100%;
    word-wrap: break-word; /*强制换行*/
    overflow: hidden; /*超出隐藏*/
    text-overflow: ellipsis; /*隐藏后添加省略号*/
    white-space: nowrap; /*强制不换行*/
    font-size: 13px;
    text-align: center;
  }
}


/* 动画代码 */
@keyframes blink {
  from {
    background-color: #f6c1c1;
  }
  to {
    background-color: #e8e8af;
  }
}
</style>